<template>
  <scroll-view style="padding-bottom: 100rpx">
    <view
      class="imgs"
      :style="{ backgroundImage: `url(${detail.goods_big_img})` }"
    ></view>
    <view class="shares" style="">
      <view class="priceBox">
        <view
          >参考价：￥<text class="price">{{
            priceVal == 0 ? "价格面议" : priceVal
          }}</text></view
        >
        <view
          ><uni-icons @click="shares.open()" type="redo" size="24"></uni-icons
        ></view>
      </view>
      <view class="priceSon">{{ nameVal }}</view>
      <view class="priceSon">
        <!-- <text class="goodsType"
          >{{ nameVal }}</text
        > -->
      </view>
    </view>
    <view
      style="
        background-color: #fff;
        margin-top: 10rpx;
        padding: 20rpx;
        padding-bottom: 60rpx;
      "
    >
      <view
        v-for="item in detail.spec_group"
        :key="item.group_id"
        style="margin-top: 20rpx"
      >
        <view
          class="spenTitle"
          v-if="item.children && item.children.length > 0"
          >{{ item.group_name }}</view
        >
        <view
          style="display: flex; flex-wrap: wrap; gap: 10rpx"
          v-if="item.children && item.children.length > 0"
        >
          <text
            v-for="sonItem in item.children"
            :key="sonItem.value_id"
            style="margin-left: 10rpx; font-size: 24rpx"
            :class="
              formOptions[`spec_${item.group_id}`] == sonItem.value_id
                ? 'specItemCheck'
                : 'specItem'
            "
            @click="checkSpec(item, sonItem)"
          >
            {{ sonItem.value_name }}<template v-if="sonItem.attr_name">【{{ sonItem.attr_name }}】</template>
          </text>
        </view>
      </view>
    </view>
    <uni-popup ref="shares" type="share" safeArea backgroundColor="#fff">
      <share></share>
    </uni-popup>

    <uni-goods-nav
      class="bottomNav"
      :fill="true"
      :options="options"
      :button-group="buttonGroup"
      @click="ImgClick"
      @buttonClick="buttonClick"
    />
  </scroll-view>
  <uni-popup ref="popup" type="bottom" background-color="#fff">
    <view class="popup-content">
      <view>{{ name }}</view>
      <view style="display: flex; justify-content: space-between">
        <view>购买数量</view>
        <view><uni-number-box v-model="formOptions.num"></uni-number-box></view>
      </view>
      <view style="display: flex; justify-content: center">
        <view class="btns" @click="submit">加入清单</view>
      </view>
    </view>
  </uni-popup>
  <button
    open-type="contact"
    ref="btnContact"
    class="btnContact btnContactForDetail"
    id="btnContactForDetail"
  ></button>
</template>

<script setup>
import share from "./components/share.vue";
import { onMounted, ref, computed, watch } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { getGoodsDetail, addCarts } from "@/api/index.js";
import { getUser } from "@/utils/token.js";
const btnContact = ref(null);
const formOptions = ref({
  num: 1,
  selectedSpecs: {}, // 用于存储已选择的规格
});
// 定义一个默认被选中的数据

function checkSpec(item, son) {
  // 如果点击的是当前选中的规格，则取消选中
  if (formOptions.value["spec_" + item.group_id] === son.value_id) {
    formOptions.value["spec_" + item.group_id] = 0;
    formOptions.value["price_" + item.group_id] = 0;
    formOptions.value["name_" + item.group_id] = "";
  } else {
    // 选中新的规格
    formOptions.value["spec_" + item.group_id] = son.value_id;
    formOptions.value["price_" + item.group_id] = son.price || 0;
    formOptions.value["name_" + item.group_id] = `${son.value_name}${son.attr_name ? `【${son.attr_name}】` : ''}`;
  }

  // 更新商品详情
  updateGoodsDetail();
}

function updateGoodsDetail() {
  const selectedSpecs = [];
  const selectedValues = [];

  // 收集已选择的规格ID和值ID
  Object.keys(formOptions.value).forEach((key) => {
    if (key.startsWith("spec_") && formOptions.value[key] !== 0) {
      const groupId = key.split("_")[1];
      selectedSpecs.push(groupId);
      selectedValues.push(formOptions.value[key]);
    }
  });

  // 更新groupid和value_id
  groupid.value = selectedSpecs;
  value_id.value = selectedValues;

  // 重新获取商品详情
  getList();
}
const priceVal = ref(0);
const nameVal = ref("");
const spec = ref([]);
watch(
  () => formOptions.value,
  (newVal) => {
    console.log("formOptions changed:", newVal);
    let sum = 0;
    let sumName = "";
    spec.value = [];

    // 遍历所有规格
    Object.keys(newVal).forEach((key) => {
      if (key.startsWith("price_")) {
        const price = newVal[key] || 0;
        sum += Number(price);
      } else if (key.startsWith("name_") && newVal[key]) {
        sumName += " " + newVal[key];
      } else if (key.startsWith("spec_") && newVal[key]) {
        spec.value.push(newVal[key]);
      }
    });

    // 更新价格和名称
    const basePrice = detail.value.price || 0;
    const totalPrice = basePrice + sum;
    price.value = totalPrice === 0 ? "价格面议" : totalPrice;
    name.value = detail.value.goods_name + sumName;

    console.log("Updated price:", price.value);
    console.log("Updated name:", name.value);
    priceVal.value = price.value;
    nameVal.value = name.value;
  },
  {
    deep: true,
    immediate: true,
  }
);

const shares = ref();
const popup = ref();
const id = ref(0);
const groupid = ref([]);
const value_id = ref([]);
onLoad((option) => {
  console.log(option, 121);
  id.value = option.id;
  // getGoodsDetail(option.id).then((e) => {
  //   console.log('商品详情数据:', e.data);
  //   console.log('规格组数据:', e.data.spec_group);
  //   detail.value = e.data;
  //   price.value = e.data.price ?? 0;
  //   name.value = e.data.goods_name;
  // });
  getList();
});
function getList() {
  getGoodsDetail(
    id.value,
    groupid.value.join(","),
    value_id.value.join(",")
  ).then((e) => {
    console.log("商品详情数据:", e.data);
    console.log("规格组数据:", e.data.spec_group);
    detail.value = e.data;
    price.value = e.data.price ?? 0;
    name.value = e.data.goods_name;

    // 初始化规格选择
    if (e.data.spec_group && e.data.spec_group.length > 0) {
      e.data.spec_group.forEach((group) => {
        if (group.children && group.children.length > 0) {
          const firstChild = group.children[0];
          formOptions.value["spec_" + group.group_id] = firstChild.value_id;
          formOptions.value["price_" + group.group_id] = firstChild.price || 0;
          formOptions.value["name_" + group.group_id] = `${firstChild.value_name}${firstChild.attr_name ? `【${firstChild.attr_name}】` : ''}`;
        }
      });
    }
  });
}

const detail = ref({});

const price = ref(0);
const name = ref("");
const options = ref([
  {
    icon: "chat",
    text: "客服",
  },
  {
    icon: "shop",
    text: "首页",
  },
  {
    icon: "list",
    text: "清单",
  },
]);

const buttonGroup = ref([
  {
    text: "加入清单",
    backgroundColor: "#E60012",
    color: "#fff",
  },
]);

function ImgClick(item) {
  console.log(item, 78);
  if (item.content.icon === "chat") {
    console.log("点击了聊天");
    // #ifdef MP-WEIXIN
    wx.openCustomerServiceConversation({
      success: function (res) {
        console.log("成功创建客服会话");
      },
      fail: function (error) {
        console.log("创建客服会话失败", error);
      },
    });
    // #endif
  } else if (item.content.icon === "shop") {
    uni.switchTab({
      url: "/pages/index/index",
    });
  } else {
    console.log("清单");
    uni.switchTab({
      url: "/pages/qingDan/index",
    });
  }
}

function buttonClick(item) {
  if (getUser()) {
    popup.value.open();
  } else {
    uni.navigateTo({
      url: "/wuLian/pages/login",
    });
  }
}
/**
 * customer_id
 * goods_id
 * num
 * spec_ids
 */
function submit() {
  const user = getUser();
  let submitOption = {};
  submitOption.customer_id = user.id;
  submitOption.goods_id = detail.value.id;
  submitOption.num = formOptions.value.num;
  submitOption.spec_ids = spec.value.join();
  uni.showLoading({
    title: "加载中...",
  });
  addCarts(submitOption).then((e) => {
    // console.log(e)
    // 保存成功 跳转到 清单页面
    uni.hideLoading();
    if (e.code == 0) {
      uni.showToast({
        title: "加入清单成功",
        icon: "success",
      });
    } else {
      uni.showToast({
        title: e.msg,
        icon: "none",
      });
    }
    popup.value.close();
    // uni.switchTab({
    //   url: "/pages/qingDan/index",
    // });
  });
}
</script>

<style lang="scss" scoped>
.price {
  font-size: 48rpx;
  color: red;
}

.imgs {
  width: 100%;
  height: 568rpx;
  background-position: center;
  background-repeat: no-repeat;
  background-size: contain;
  background-color: #fff;
}

.priceBox {
  display: flex;
  justify-content: space-between;
  padding: 0rpx 10rpx;
}

.shares {
  width: 100%;
  height: 200rpx;
  margin-top: 10rpx;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.priceSon {
  padding: 10rpx;
}

.spenTitle {
  font-size: 32rpx;
  font-weight: 600;
  padding-bottom: 10rpx;
  border-bottom: 1px solid #fdfdfd;
  margin-bottom: 20rpx;
}

.specItem {
  padding: 2rpx 20rpx;
  border-radius: 5rpx;
  border: 1rpx solid #e60012;
  color: #e60012;
}

.specItemCheck {
  padding: 2rpx 20rpx;
  border-radius: 5rpx;
  border: 1rpx solid #e60012;
  color: #fff;
  background-color: #e60012;
}

.bottomNav {
  position: fixed;
  bottom: 0rpx;
  width: 100%;
  padding-bottom: 30rpx;
}

.goodsType {
  font-size: 24rpx;
  background-color: #e60012;
  color: #fff;
  padding: 5rpx 20rpx;
  border-radius: 5rpx;
}

.popup-content {
  padding: 20rpx;
  height: 200rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  border-radius: 30rpx;
  background-color: #fff;
}

.btns {
  background-color: #e60012;
  color: #fff;
  padding: 10rpx 20rpx;
  border-radius: 10rpx;
  width: 40%;
  text-align: center;
}
</style>
